package com.zjsos.governmentaffairs.sokettestapplication.socketClientNew;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;

public class NettyClientHandlerNew extends ChannelInboundHandlerAdapter {


    private final String TAG = "Netty";
    private HandlerThread workThread;
    private Handler workHandler;        //子线程handler，在主线程发送消息，子线程处理消息
    public static final int RECEIVE_MESSAGE_CODE=100;
    private NettyListener listener;

    private boolean isWait;
    private byte[] receiveBytes;
    private int sendHeartMethodCode,sendHeartStructCode;

    public NettyClientHandlerNew(NettyListener listener) {
        this.listener = listener;
//        sendHeartMethodCode=StreamUtils.getMethodHashcode("MyHeartbeat");
//        sendHeartStructCode=StreamUtils.getMethodHashcode("struct MyCTP::Heartbeat");
        //收到消息后放入子线程消息队列
        workThread=new HandlerThread("workHandler");
        workThread.start();
        workHandler=new Handler(workThread.getLooper()){
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what){
                    case RECEIVE_MESSAGE_CODE:
//                        parseBytes(msg.obj);
                        byte[] bytes= (byte[]) msg.obj;
                        Log.e("test",new String(bytes));
                        break;
                }
            }
        };
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Log.e(TAG, "channel active");
        super.channelActive(ctx);
        NettyClientNew.getInstance().setConnectStatus(true);
        listener.onServiceStatusConnectChanged(NettyListener.STATUS_CONNECT_SUCCESS);
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Log.e("test","收到就回消息。。。");
        ByteBuf buf = (ByteBuf) msg;
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        Message message=new Message();
        message.what=RECEIVE_MESSAGE_CODE;
        message.obj=req;
        workHandler.sendMessage(message);

    }
/*

    private void parseBytes(Object msg) {
        ByteBuf buf = (ByteBuf) msg;
        if (buf.readableBytes()==0){
            return;
        }
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        Log.e("test","收到消息长度wei:"+req.length);

        byte[] totalBytes=null;
        if (isWait&&receiveBytes!=null){
            totalBytes=new byte[receiveBytes.length+req.length];
            System.arraycopy(receiveBytes,0,totalBytes,0,receiveBytes.length);
            System.arraycopy(req,0,totalBytes,receiveBytes.length,req.length);
            isWait=false;
        }else {
            totalBytes=req;
        }
        parseBytesDetail(totalBytes);
    }

    public void parseBytesDetail(byte[] totalBytes){
        //查找开头的四个字节{-1,-1,-1,-1}
        int startIndex=JNIUtils.byteArray2Position(totalBytes);
        if (startIndex==-1){
            isWait=true;
            receiveBytes=totalBytes;
            return;
        }

        if (totalBytes.length - startIndex < 12){
            isWait=true;
            receiveBytes=totalBytes;
            return;
        }

        byte[] headFBytes = new byte[12];
        System.arraycopy(totalBytes, startIndex, headFBytes, 0, 12);
//        Log.e("test","转包之前的headArray="+ Arrays.toString(headFBytes));
        PackageHeaderBean bean = JNIUtils.byteArray2PackageHeader(headFBytes);
//        Log.e("test", "bean.getHeaderLength()="+bean.getHeaderLength());

        if (startIndex + bean.getHeaderLength() + 12 > totalBytes.length){
            isWait=true;
            receiveBytes=totalBytes;
            return;
        }

        byte[] headBytes = new byte[bean.getHeaderLength()];
        System.arraycopy(totalBytes, startIndex + 12, headBytes, 0, bean.getHeaderLength());
        byte[] headCompressBytes = StreamUtils.decompress(headBytes);
        Protobuf.Header headerPf = null;
        try {
            headerPf = Protobuf.Header.parseFrom(headCompressBytes);
//            Log.e("test","getSession="+headerPf.getSession().toStringUtf8());
            SPUtils.setSharedStringData(SPUtils.SessionId,headerPf.getSession().toStringUtf8());
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }

//        Log.e("test", "bean.getContentLength()="+bean.getContentLength());

        // 还有部分数据都丢了TODO
        if (bean.getContentLength() <= 0){
            if (totalBytes.length>12){
                byte[] remainBytes=new byte[totalBytes.length-12];
                System.arraycopy(totalBytes,12,remainBytes,0,remainBytes.length);
                isWait=false;
                receiveBytes=null;
                parseBytesDetail(remainBytes);
                return;
            }
            isWait=false;
            receiveBytes=null;
            return;
        }

        if (startIndex + bean.getHeaderLength() + 12 + bean.getContentLength() > totalBytes.length){
            isWait=true;
            receiveBytes=totalBytes;
            return;
        }

        byte[] contentBytes = new byte[bean.getContentLength()];
        System.arraycopy(totalBytes, startIndex + bean.getHeaderLength() + 12, contentBytes, 0, bean.getContentLength());
        byte[] contentC = StreamUtils.decompress(contentBytes);

        if (headerPf == null) {
            // 还有部分数据都丢了TODO
            ToastUtil.showShort("数据解析失败！");
            isWait=false;
            receiveBytes=null;
            return;
        }


        //根据返回码确定不同的返回类型
        int responseMethodC = headerPf.getRequestType();
        int responseStructC = headerPf.getStructType();

//        Message message=new Message();
//        message.what=SEND_MESSAGE_CODE;
//        Bundle bundle=new Bundle();
//        bundle.putInt("responseMethodC",responseMethodC);
//        bundle.putInt("responseStructC",responseStructC);
//        bundle.putByteArray("contentBytes",contentC);
//        message.setData(bundle);
//        mainHandler.sendMessage(message);

        MsgEventBean bean2=new MsgEventBean(responseMethodC,responseStructC,contentC);
        listener.onMessageResponse(bean2);

        // 内容和头都解析完之后剩余的存入缓存接下次
        if (startIndex + bean.getHeaderLength() + 12 + bean.getContentLength() < totalBytes.length){
            int surplusLength=totalBytes.length-startIndex-bean.getHeaderLength()-12-bean.getContentLength();
            byte[] surplusBytes=new byte[surplusLength];
            System.arraycopy(totalBytes,totalBytes.length-surplusLength,surplusBytes,0,surplusLength);
            isWait=true;
            receiveBytes=surplusBytes;
            //剩余的重新解析一遍
            parseBytesDetail(receiveBytes);
        }else {
            receiveBytes=null;
        }
    }

*/

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        NettyClientNew.getInstance().setConnectStatus(false);
        listener.onServiceStatusConnectChanged(NettyListener.STATUS_CONNECT_CLOSED);
        NettyClientNew.getInstance().sendReConnectMessage();
    }


    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            switch (e.state()) {
                case READER_IDLE:
                    //读取超时 重联操作
                    Log.e(TAG,"===服务端=== （Reader_IDLE 读超时）");
                    break;
                case WRITER_IDLE:
                    //写取超时 发送心跳包
                    Log.e(TAG,"===服务端=== （Reader_IDLE 写超时）");
//                    byte[] bytes=JNIUtils.heartString2Bytes("安卓");
//                    NettyClientNew.getInstance().sendContentMessage(bytes,sendHeartMethodCode,sendHeartStructCode);
                    break;
                case ALL_IDLE:
                    //总取超时
                    Log.e(TAG,"===服务端=== （Reader_IDLE 总超时）");
                    break;
            }
        }
    }




}